<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Session;

header('Access-Control-Allow-Origin:*');
header("Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept,USER_ID,TOKEN");
header("Access-Control-Allow-Methods:HEAD, GET, POST, DELETE, PUT, OPTIONS");

//微信支付类
class weixinpay extends Controller {
    public function pay()
    {
        vendor('Wxpay.lib.WxPay#Config');
        $headers =array();
        $headers[] ='Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
        $headers[] ='Connection: Keep-Alive';
        $headers[] ='Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3';
        $headers[] ='Accept-Encoding: gzip, deflate';
        $headers[] ='User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20100101Firefox/22.0';

        $appid ="wxcc8d1ac2b7e86c10";//微信开发者账号
        $mch_id ="1375397102";//微信官方的商户账号
        $nonce_str=$this->getNonceStr();//随机字符串
        $timeStamp=$this->getMillisecond();
        $addrip =$this->get_client_ip();

        $money = $_GET['money'];

        if ($money) {
            //签名的格式
            $signType ="MD5";
            $body="拾友账户余额充值";
            $attach="这是测试！";

            $out_trade_no=$nonce_str;
            $total_fee =$money*100; //金额

            //终端ip
            $spbill_create_ip= $addrip;
            $notify_url ="http://tour.mgtvshop.com/index/notify/index";
            $trade_type ='MWEB';//交易类型 具体看API 里面有详细介绍
            $scene_info ='{"h5_info":{"type":"Wap","wap_url":"http://tour.mgtvshop.com","wap_name":"拾友"}}';//场景信息 必要参数
            //签名
            $key ="cf9cb68e058ab61a2cf33ff1fa2ded51";//自己设置的微信商户key

            $signA="appid=$appid&attach=$attach&body=$body&mch_id=$mch_id&nonce_str=$nonce_str&notify_url=$notify_url&out_trade_no=$out_trade_no&scene_info=$scene_info&spbill_create_ip=$spbill_create_ip&total_fee=$total_fee&trade_type=$trade_type";
            $strSignTmp =$signA."&key=$key"; //拼接字符串  注意顺序微信有个测试网址 顺序按照他的来 直接点下面的校正测试 包括下面XML  是否正确
            $sign =strtoupper(MD5($strSignTmp)); // MD5 后转换成大写

            $post_data="
                <xml>
                    <appid>$appid</appid>
                    <attach>$attach</attach>
                    <body>$body</body>
                    <mch_id>$mch_id</mch_id>
                    <nonce_str>$nonce_str</nonce_str>  
                    <notify_url>$notify_url</notify_url>
                    <out_trade_no>$out_trade_no</out_trade_no>
                    <scene_info>$scene_info</scene_info>  
                    <spbill_create_ip>$spbill_create_ip</spbill_create_ip>
                    <total_fee>$total_fee</total_fee>
                    <trade_type>$trade_type</trade_type>  
                    <sign>$sign</sign>
                </xml>";//拼接成XML 格式

            $url ="https://api.mch.weixin.qq.com/pay/unifiedorder";//微信传参地址
            $dataxml =$this->http_post($url,$post_data,$headers);//向微信传参地址做请求
            $dataxml2 =json_decode(json_encode(simplexml_load_string($dataxml, 'SimpleXMLElement',LIBXML_NOCDATA)), true);//将获得的xml数据转成数组，取出MWEB_URL，

//            file_put_contents(RUNTIME_PATH.'dataxml2.txt',json_encode($dataxml2));
            $redirect_url =urlencode("http://www.baidu.com");
            $url2 =$dataxml2['mweb_url']."&redirect_url=".$redirect_url;
//            file_put_contents(RUNTIME_PATH.'url2.txt',$url2);
            header("Location:".$url2);//调起MWEB_URL，调起微信支付后台进行支付，支付后调用重定向返回到指定页面
        }else{
            return json(['code' => -1, 'msg' => '充值金额不能为空！']);
        }
    }

    //发送统一下单的函数
    public function http_post($url='',$post_data=array(),$header=array(),$timeout=30) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);  // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_TIMEOUT,$timeout);

        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
    //获取ip
    // public function get_client_ip_old($type = 0,$adv=false) {
    //     $cip = "unknown";
    //     if ($_SERVER['REMOTE_ADDR']) {
    //     $cip = $_SERVER['REMOTE_ADDR'];
    //     } else if (getenv("REMOTE_ADDR")){
    //         $cip = getenv("REMOTE_ADDR");
    //     }
    //     return $cip;
    // }

    function get_client_ip(){
        if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'),'unknown')) {

            $ip = getenv('HTTP_CLIENT_IP');

        } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'),'unknown')) {

            $ip = getenv('HTTP_X_FORWARDED_FOR');

        } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'),'unknown')) {

            $ip = getenv('REMOTE_ADDR');

        } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {

            $ip = $_SERVER['REMOTE_ADDR'];

        }

        return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
    }

    //获取随机字符串
    public function getNonceStr($length = 32) {
        $chars ="abcdefghijklmnopqrstuvwxyz0123456789";
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {
            $str .= substr($chars, mt_rand(0,strlen($chars)-1), 1);
        }
        return $str;
    }
    //获取时间戳
    public function getMillisecond() {
        //获取毫秒的时间戳
        $time = explode ( " ", microtime() );
        $time = $time[1] . ($time[0] * 1000);
        $time2 = explode( ".", $time );
        $time = $time2[0];
        return $time;
    }
}